package com.xian.im.config;

import com.google.common.eventbus.AsyncEventBus;
import com.xian.im.common.properties.AsyncProperties;
import com.xian.im.config.thread.DefaultNamedThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 开启异步线程池
 *
 * @author xlr
 */
@SuppressWarnings("UnstableApiUsage")
@EnableAsync
@Configuration(value = "poolConfig")
public class AsyncPoolConfig extends AsyncConfigurerSupport {

    public static final String THREAD_FACTORY_NAME = "dynamic-executor";

    @Autowired
    AsyncProperties asyncProperties;

    @Bean
    public Executor dynamicTaskExecutor() {
        return new ThreadPoolExecutor(
                asyncProperties.getCorePoolSize(),
                asyncProperties.getMaxPoolSize(),
                asyncProperties.getKeepAliveSeconds().longValue(),
                TimeUnit.SECONDS,
                new ResizableCapacityLinkedBlockingQueue(),
                new DefaultNamedThreadFactory(asyncProperties.getThreadNamePrefix()),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    /**
     *  消息总线
     * @return
     */
    @Bean
    public AsyncEventBus asyncEventBus(){
       return new AsyncEventBus(dynamicTaskExecutor());
    }
}
